﻿using System.Text;
using T4UtilityBelt.Writers;

namespace T4UtilityBelt.UxDesigns.Bindings.Android
{
    public class BindingRenderer : IBindingRenderer
    {
        public void Render(CodeWriter writer, string property, Binding binding)
        {
            if (binding != null)
            {
                // local:MvxBind="ItemsSource UpdateFrequencies; SelectedItem UpdateFrequency, Mode=TwoWay"
                writer.AddBindingToList(property, binding);
            }
        }


        public void RenderBindingsAttribute(CodeWriter codeWriter, BindingDictionary bindings)
        {
            if (bindings.Count > 0)
            {
                codeWriter.WriteAttribute("local:MvxBind", Render(bindings));
                bindings.Clear();
            }
        }

        private static string Render(BindingDictionary bindings)
        {
            if (bindings == null)
                return null;

            var sb = new StringBuilder();
            foreach (var pair in bindings)
            {
                Binding binding = pair.Value;
                if (binding != null)
                {
                    if (sb.Length > 0)
                    {
                        sb.Append("; ");
                    }
                    sb.Append(pair.Key);

                    sb.Append(" ");

                    sb.Append(binding.SourcePropertyPath);

                    if (!string.IsNullOrEmpty(binding.Converter))
                    {
                        sb.Append(", Converter=");
                        sb.Append(binding.Converter);
                        if (binding.ConverterParameter != null)
                        {
                            sb.Append(", ConverterParameter=");
                            sb.Append(binding.ConverterParameter);
                        }
                    }

                    if (binding.FallbackValue != null)
                    {
                        sb.Append(", FallbackValue=");
                        sb.Append(binding.FallbackValue);
                    }

                    if (binding.Mode != BindingMode.Default)
                    {
                        sb.Append(", Mode=");
                        sb.Append(binding.Mode);
                    }
                }
            }

            return sb.ToString();
        }
    }
}